﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


using ThoiTrang.Business;
using ThoiTrang.Entities;


public partial class adm_user_list : System.Web.UI.Page
{
    public  string ckid="";

    protected void Page_Load(object sender, EventArgs e)
    {
      
        if (!IsPostBack)
        {
            a_Session ss = null;
            a_User usr = null;
            a_UserType usrType = null;
            if (SessionManager.IsLogged)
            {
                ss = a_SessionService.Geta_Session(SessionManager.GetCookie());
                ckid = ss.SessionID;
                usr = a_UserService.Geta_User(ss.CookieID);
                usrType = a_UserTypeService.Geta_UserType(usr.UserTypeID);
                this.lblGretting.Text = "Hi " + usr.Firstname + " " + usr.Lastname;

                switch (usrType.AccessLevel)
                {
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        break;
                }

                txtDateFrom.Text = DateTime.Now.Subtract(new TimeSpan(1000, 0, 0, 0)).ToString("dd/MM/yyyy");
                txtDateTo.Text = DateTime.Now.AddDays(1).ToString("dd/MM/yyyy");

                this._ReadParam();
                this._BindDataGrid();
            }
        }
    }

    private void _ReadParam()
    {
        if (Request.Params["st"] != null && Request.Params["issys"]==null)
        {
            this.grvSearchResult.Columns[8].Visible=false;
            this.grvSearchResult.Columns[9].Visible=false;
        }
        //else if(Request.Params["issys"]!=null && Request.Params["issys"]=="1")
        //{
        //    this.grvSearchResult.Columns[7];
        //}
        if (Request.Params["fDateFrom"] != null)
        {
            this.txtDateFrom.Text = Request.Params["fDateFrom"].ToString();
        }
        if (Request.Params["fDateTo"] != null)
        {
            this.txtDateTo.Text = Request.Params["fDateTo"].ToString();
        }
        if (Request.Params["sb"] != null)
        {
            this.ddlSortBy.SelectedValue = Request.Params["sb"].ToString();
        }
        if (Request.Params["sfield"] != null)
        {
            this.ddlSearchBy.SelectedValue = Request.Params["sfield"].ToString();
        }
        if (Request.Params["svalue"] != null)
        {
            this.txtSearchBy.Text = Request.Params["svalue"].ToString();
        }
        if (Request.Params["so"] != null)
        {
            this.ddlSortOrder.SelectedValue = Request.Params["so"].ToString();
        }
    }

    private void _BindDataGrid()
    {
        #region Read params
        string fDateFrom, fDateTo, sb, so, sfield, svalue, issys, p;
        string usertype = "";
        bool st;
        //Readparams
        if (Request.Params["fDateFrom"] != null)
        {
            fDateFrom =this.ProcessDate( Request.Params["fDateFrom"].ToString());
        }
        else
        {
            if (this.txtDateFrom.Text != "")
            {
                fDateFrom =this.ProcessDate( this.txtDateFrom.Text);
            }
            else
            {
                fDateFrom = "1/1/1900";
            }
        }
        if (Request.Params["fDateTo"] != null)
        {
            fDateTo =ProcessDate( Request.Params["fDateTo"].ToString());
        }
        else
        {
            if (this.txtDateTo.Text != "")
            {
                fDateTo = ProcessDate(this.txtDateTo.Text);
            }
            else
            {
                fDateTo = "1/1/1900";
            }
        }
        if (Request.Params["sb"] != null)
        {
            sb = Request.Params["sb"].ToString();
        }
        else
        {
            sb = this.ddlSortBy.SelectedValue;
        }
        if (Request.Params["so"] != null)
        {
            so = Request.Params["so"].ToString();
        }
        else
        {
            if (this.ddlSortBy.SelectedIndex > 0)
            {
                so = this.ddlSortOrder.SelectedValue;
            }
            else
            {
                so = "ASC";
            }
        }
        if (Request.Params["sfield"] != null)
        {
            sfield = Request.Params["sfield"].ToString();
        }
        else
        {
            sfield= this.ddlSearchBy.SelectedValue;
        }
        if (Request.Params["svalue"] != null)
        {
            svalue = Request.Params["svalue"].ToString();
        }
        else
        {
            svalue = this.txtSearchBy.Text;
        }
        if (Request.Params["st"] != null)
        {
            if (Request.Params["st"].ToString() == "1")
            {
                st = true;
            }
            else
            {
                st = false;
            }
        }
        else
        {
            st = false;
        }
        if (Request.Params["issys"] != null)
        {
            issys = Request.Params["issys"].ToString();
            usertype = "2,3";
            st = true;
        }
        else
        {
            issys = "";
        }
        if (Request.Params["p"] != null)
        {
            p = Request.Params["p"].ToString();
        }
        else
        {
            p = "1";
        }
        ThoiTrang.Data.OrderDirection objDirection = ThoiTrang.Data.OrderDirection.ASC;
        if (so == "DESC")
        {
            objDirection = ThoiTrang.Data.OrderDirection.DESC;
        }
        else
        {
            objDirection = ThoiTrang.Data.OrderDirection.ASC;
        }
        a_UserColumns objColumns = a_UserColumns.Login_Email;
        if (sb == "Login_Email")
        {
            objColumns = a_UserColumns.Login_Email;
        }
        else if (sb == "Firstname")
        {
            objColumns = a_UserColumns.Firstname;
        }
        else if (sb == "Lastname")
        {
            objColumns = a_UserColumns.Lastname;
        }
        #endregion

        int totalrecords=0;
        if (usertype != "")
        {
            this.grvSearchResult.DataSource = a_UserService.Geta_UserList_search(usertype, st, sfield, svalue, DateTime.Parse(fDateFrom), DateTime.Parse(fDateTo),a_UserColumns.UserTypeID,ThoiTrang.Data.OrderDirection.ASC, int.Parse(p), 50, out totalrecords);
        }
        else
        {
            this.grvSearchResult.DataSource = a_UserService.Geta_UserList_search(usertype, st, sfield, svalue, DateTime.Parse(fDateFrom), DateTime.Parse(fDateTo), objColumns, objDirection, int.Parse(p), 50, out totalrecords);
        }
        this.grvSearchResult.DataBind();
        int nopage=1;
        if(totalrecords % 50==0)
        {
            nopage=totalrecords/50;
        }
        else
        {
            nopage=totalrecords/50 +1;
        }
        AdminPagingListing1.Total = totalrecords;
        AdminPagingListing2.Total = totalrecords;
        //this.ltrPaging.Text = CommonFunc.QueryPaging(int.Parse(p), nopage, 5);
        //this.ltrPaging2.Text = CommonFunc.QueryPaging(int.Parse(p), nopage, 5);
        if (totalrecords == 0)
        {
            this.ltrStatic.Text = "No record found for this period.";
        }
        else
        {
            this.ltrStatic.Text = "Page " + p + "    |   " + totalrecords.ToString() + " records found";
        }
    }

    private string ProcessDate(string strDate)
    {
        try
        {
            string[] arrDate = strDate.Split("/".ToCharArray());
            return arrDate[1] +"/"+ arrDate[0] +"/"+ arrDate[2];
        }
        catch (Exception ex) { return strDate; }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.RedirectByCondition();
    }
    protected void btnFillter_Click(object sender, EventArgs e)
    {
        this.RedirectByCondition();
    }

    private void RedirectByCondition()
    {
        //this._BindDataGrid();
        string url = this.Request.Url.ToString();
        if (Request.QueryString["fDateFrom"] != null && Request.QueryString["fDateFrom"].ToString() != this.txtDateFrom.Text)
        {
            try
            {
                url = url.Replace(Request.QueryString["fDateFrom"].ToString(), this.txtDateFrom.Text);
            }
            catch (Exception ex)
            {
                url = url.Insert(url.IndexOf("&fDateFrom=") + "&fDateFrom=".Length, this.txtDateFrom.Text);
            }
        }
        else if (Request.QueryString["fDateFrom"] == null)
        {
            url += "&fDateFrom=" + this.txtDateFrom.Text;
        }

        if (Request.QueryString["fDateTo"] != null && Request.QueryString["fDateTo"].ToString() != this.txtDateTo.Text)
        {
            try
            {
                url = url.Replace(Request.QueryString["fDateTo"].ToString(), this.txtDateTo.Text);
            }
            catch (Exception ex)
            {
                url = url.Insert(url.IndexOf("&fDateTo=") + "&fDateTo=".Length, this.txtDateTo.Text);
            }
        }
        else if (Request.QueryString["fDateTo"] == null)
        {
            url += "&fDateTo=" + this.txtDateTo.Text;
        }

        if (Request.QueryString["sb"] != null && Request.QueryString["sb"].ToString() != this.ddlSortBy.SelectedValue)
        {
            try
            {
                url = url.Replace(Request.QueryString["sb"].ToString(), this.ddlSortBy.SelectedValue);
            }
            catch (Exception ex)
            {
                url = url.Insert(url.IndexOf("&sb=") + "&sb=".Length, this.ddlSortBy.SelectedValue);
            }
        }
        else if (Request.QueryString["sb"] == null)
        {
            url += "&sb=" + this.ddlSortBy.SelectedValue;
        }

        if (Request.QueryString["so"] != null && Request.QueryString["so"].ToString() != this.ddlSortOrder.SelectedValue)
        {
            try
            {
                url = url.Replace(Request.QueryString["so"].ToString(), this.ddlSortOrder.SelectedValue);
            }
            catch (Exception ex)
            {
                url = url.Insert(url.IndexOf("&so=") + "&so=".Length, this.ddlSortOrder.SelectedValue);
            }
        }
        else if (Request.QueryString["so"] == null)
        {
            url += "&so=" + this.ddlSortOrder.SelectedValue;
        }

        if (Request.QueryString["sfield"] != null && Request.QueryString["sfield"].ToString() != this.ddlSearchBy.SelectedValue)
        {
            try
            {
                url = url.Replace(Request.QueryString["sfield"].ToString(), this.ddlSearchBy.SelectedValue);
            }
            catch (Exception ex)
            {
                url = url.Insert(url.IndexOf("&sfield=") + "&sfield=".Length, this.ddlSearchBy.SelectedValue);
            }
        }
        else if (Request.QueryString["sfield"] == null)
        {
            url += "&sfield=" + this.ddlSearchBy.SelectedValue;
        }

        if (Request.QueryString["svalue"] != null && Request.QueryString["svalue"].ToString() != this.txtSearchBy.Text)
        {
            try
            {
                url = url.Remove(url.LastIndexOf("&svalue=") + "&svalue=".Length, Request.QueryString["svalue"].ToString().Length);
                url = url.Insert(url.IndexOf("&svalue=") + "&svalue=".Length, this.txtSearchBy.Text);
            }
            catch (Exception ex)
            {
                url = url.Insert(url.IndexOf("&svalue=") + "&svalue=".Length, this.txtSearchBy.Text);
            }
        }
        else if (Request.QueryString["svalue"] == null)
        {
            url += "&svalue=" + this.txtSearchBy.Text;
        }

        Response.Redirect(System.Web.HttpUtility.UrlDecode( url));
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect(HttpContext.Current.Request.Url.ToString());
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow r in grvSearchResult.Rows)
        {
            CheckBox chk = (CheckBox)r.FindControl("chkSelect");
            if (chk.Checked)
            {
                string key= grvSearchResult.DataKeys[r.RowIndex].Value.ToString();
                a_UserService.Deletea_User(int.Parse(key));
            }
        }
        this._BindDataGrid();
        CommonFunc.ShowAlertMessage(this.lblAlert, "Delete sucessfully");
    }

    public string Paging(int totalRecord, int recPerPage, int pageSet)
    {
        #region Read params
        string fDateFrom, fDateTo, sb, so, sfield, svalue, issys, p;
        bool st;
        //Readparams
        if (Request.Params["fDateFrom"] != null)
        {
            fDateFrom = Request.Params["fDateFrom"].ToString();
        }
        else
        {
            if (this.txtDateFrom.Text != "")
            {
                fDateFrom = this.txtDateFrom.Text;
            }
            else
            {
                fDateFrom = "1/1/1900";
            }
        }
        if (Request.Params["fDateTo"] != null)
        {
            fDateTo = Request.Params["fDateTo"].ToString();
        }
        else
        {
            if (this.txtDateTo.Text != "")
            {
                fDateTo = this.txtDateTo.Text;
            }
            else
            {
                fDateTo = "1/1/1900";
            }
        }
        if (Request.Params["sb"] != null)
        {
            sb = Request.Params["sb"].ToString();
        }
        else
        {
            sb = this.ddlSortBy.SelectedValue;
        }
        if (Request.Params["so"] != null)
        {
            so = Request.Params["so"].ToString();
        }
        else
        {
            if (this.ddlSortBy.SelectedIndex > 0)
            {
                so = this.ddlSortOrder.SelectedValue;
            }
            else
            {
                so = "ASC";
            }
        }
        if (Request.Params["sfield"] != null)
        {
            sfield = Request.Params["sfield"].ToString();
        }
        else
        {
            sfield = this.ddlSearchBy.SelectedValue;
        }
        if (Request.Params["svalue"] != null)
        {
            svalue = Request.Params["svalue"].ToString();
        }
        else
        {
            svalue = this.txtSearchBy.Text;
        }
        if (Request.Params["st"] != null)
        {
            if (Request.Params["st"].ToString() == "1")
            {
                st = true;
            }
            else
            {
                st = false;
            }
        }
        else
        {
            st = false;
        }
        if (Request.Params["issys"] != null)
        {
            issys = Request.Params["issys"].ToString();
        }
        else
        {
            issys = "";
        }
        if (Request.Params["p"] != null)
        {
            p = Request.Params["p"].ToString();
        }
        else
        {
            p = "1";
        }
        ThoiTrang.Data.OrderDirection objDirection = ThoiTrang.Data.OrderDirection.ASC;
        if (so == "ASC")
        {
            objDirection = ThoiTrang.Data.OrderDirection.ASC;
        }
        else
        {
            objDirection = ThoiTrang.Data.OrderDirection.DESC;
        }
        a_UserColumns objColumns = a_UserColumns.Login_Email;
        if (sb == "Login_Email")
        {
            objColumns = a_UserColumns.Login_Email;
        }
        else if (sb == "Firstname")
        {
            objColumns = a_UserColumns.Firstname;
        }
        else if (sb == "Lastname")
        {
            objColumns = a_UserColumns.Lastname;
        }
        #endregion

        string currentUrl = HttpContext.Current.Request.Url.ToString();

        int currentPage = HttpContext.Current.Request.QueryString["p"] == null ? 1 : Convert.ToInt32(HttpContext.Current.Request.QueryString["p"]);
        int prePage = currentPage == 1 ? 1 : currentPage - 1;
        int nextPage = currentPage + 1;
        int lastPage =totalRecord / recPerPage +1;
        
        string []parseUrl=currentUrl.Split('?');

        currentUrl = parseUrl[0];
        string currentParam = "";
        
        if (parseUrl.Length > 1)
        {
            if (st)
            {
                currentParam += "&st=1";
            }
            else
            {
                currentParam += "&st=0";
            }
            currentParam += "&so=" + so + "&sb=" + sb + "&svalue=" + svalue + "&sfield=" + sfield + "&fDateFrom=" + fDateFrom + "&fDateTo=" + fDateTo+"&ckid="+Request.Params["ckid"].ToString();
            currentParam = currentParam.Trim('&');
        }
        
        string paging = "<table class='p3 fr'><tr>";
        paging += "<td class='next-pre'><a href='" + currentUrl + "?p=1&" + currentParam + "'><img height='17' width='28' alt='thoi trang' src='../images/nav_previousset_off.gif'/></a></td>";
        paging += "<td class='next-pre'><a href='" + currentUrl + "?p=" + prePage.ToString() + "&" + currentParam + "'><img height='17' width='28' alt='thoi trang' src='../images/nav_previouspage_off.gif'/></a></td>";

        if (currentPage > pageSet)
        {
        }
        else
        {
            for (int i = 1; i < currentPage; i++)
            {
                paging += "<td class='go'><a href='" + currentUrl + "?p=" + i.ToString() + "&" + currentParam + "'>" + i.ToString() + "</a></td>";
            }
        }
        
        for (int i = currentPage; i < currentPage+pageSet; i++)
        {
            if (i==currentPage)
                paging += "<td class='current'><a href='" + currentUrl + "?p=" + i.ToString() + "&" + currentParam + "'>" + i.ToString() + "</a></td>";
            else
                paging += "<td class='go'><a href='" + currentUrl + "?p=" + i.ToString() + "&" + currentParam + "'>" + i.ToString() + "</a></td>";
        }

        paging += "<td class='next-pre'><a href='" + currentUrl + "?p=" + nextPage.ToString() + "&" + currentParam + "'><img height='17' width='28' alt='thoi trang' src='../images/nav_nextpage_on.gif'/></a></td>";
        paging += "<td class='next-pre'><a href='" + currentUrl + "?p=" + lastPage.ToString() + "&" + currentParam + "'><img height='17' width='28' alt='thoi trang' src='../images/nav_nextset_off.gif'/></a></td>";
        paging += "</tr></table>";

        return paging;
    }

    protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        DropDownList drp = (DropDownList)e.Row.FindControl("drpUserType");
        if (drp != null)
        {
            drp.SelectedValue = this.grvSearchResult.DataKeys[e.Row.RowIndex][1].ToString();
        }
        Label lbl = (Label)e.Row.FindControl("lblStatus");
        if (lbl != null)
        {
            if (lbl.Text == "True")
            {
                lbl.Text = "Approved";
            }
            else
            {
                lbl.Text = "Unapproved";
            }
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        int noupdate = 0;
        int iChecked = 0;
        foreach (GridViewRow gr in this.grvSearchResult.Rows)
        {
            CheckBox chk = (CheckBox)gr.FindControl("chkSelect");
            DropDownList drp = (DropDownList)gr.FindControl("drpUserType");
            if (chk != null && drp != null && chk.Checked)
            {
                iChecked++;
            }
        }
        if (iChecked > 0)
        {
            foreach (GridViewRow gr in this.grvSearchResult.Rows)
            {
                CheckBox chk = (CheckBox)gr.FindControl("chkSelect");
                DropDownList drp = (DropDownList)gr.FindControl("drpUserType");
                CheckBox chkIsFeatured = (CheckBox)gr.FindControl("chk");
                if (chk != null && drp != null && chk.Checked)
                {
                    //Thuc hien update
                    //Kiem tra user la gi`?
                    if (Request.Params["issys"] != null && Request.Params["issys"].ToString() == "1")
                    {
                        int uid = int.Parse(this.grvSearchResult.DataKeys[gr.RowIndex][0].ToString());
                        a_User au = a_UserService.Geta_User(uid);
                        //au.UserTypeID = int.Parse(drp.SelectedValue);
                        au.IsAccessFeatured = chkIsFeatured.Checked;
                        au.UserTypeID = int.Parse(drp.SelectedValue);
                        a_UserService.Updatea_User(au);
                        noupdate++;
                    }
                    else
                    {
                        int uid = int.Parse(this.grvSearchResult.DataKeys[gr.RowIndex][0].ToString());
                        a_User au = a_UserService.Geta_User(uid);
                        au.UserTypeID = int.Parse(drp.SelectedValue);
                        a_UserService.Updatea_User(au);
                        noupdate++;
                    }
                }
            }
            if (noupdate > 0)
            {
                CommonFunc.ShowAlertMessage(this.lblAlert, "Update sucessfully");
            }
            this._BindDataGrid();
        }
        else
        {
            CommonFunc.ShowAlertMessage(this.lblAlert, "Please check user to edit");
        }
    }
}
